#!/usr/bin/env python
#-*-encoding:utf-8-*-
'''
Created on 2015年7月21日

@author: chenyongbing
'''
import sys,os
#current_dir = os.path.dirname(__file__)
current_dir = os.path.split(os.path.realpath(__file__))[0]

'''数据暴增问题分析'''

sys.path.append(os.path.join(current_dir,'../../'))
import logging,datetime


from base.zhimind_datas import myZhimindDatas
from base.time_method import myTimeMethod
from base.retail_datas import myRetailDatas


from base.PyRedis import ConnectRedis
redisConnectList = []
for redisHost,redisPort in [['zm04',6379],['zm05',6379],['zm06',6379],['zm10',6379]]:
    redisConnectList.append(ConnectRedis(redisHost,redisPort))



def get_flow_form_redis(day=None,target='ent_cust_cnt'):
    datas = {}
    if day==None:
        day = datetime.date.today().strftime('%Y-%m-%d')
    if target == 'ent_cust_cnt':
        key = 'g_cus_cnt_%s_*'%day
    elif target == 'visit_cnt':
        key = 'g_all_cnt_%s_*'%day
        
    
    for redisConnect in redisConnectList:
        keys = redisConnect.keys(key)
        
        for k in keys:
            group = int(re.sub(key,'',k))
            ndatas = redisConnect.hgetall(k)
            count = 0
            for v in ndatas.values():
                count+=int(v)
            datas[group] = count
    return datas
    

def check_flow_mutation(tab='rank_stats',timeType='day',group=None,groupType =4,mult=8,day = None,target='ent_cust_cnt',min=min,source='mysql'):
    u'''
        验证数据是否突变;相对于前一天是否有大于N倍的增长;
    '''
    today = datetime.date.today().strftime('%Y-%m-%d')
    if day==None or day == today:
        day = datetime.date.today().strftime('%Y-%m-%d')
        hour = int(datetime.datetime.today().strftime('%H'))
    else:
        hour = 23
    yesterday = (datetime.date(int(day[:4]),int(day[5:7]),int(day[8:10])) - datetime.timedelta(1)).strftime('%Y-%m-%d')
    if hour==23:
        yest_visit_cnt =myZhimindDatas.get_one_target_from_rank_stats_by_group(timeType=timeType, group=group, groupType=groupType, st=yesterday,et = yesterday, target=target)
    else:
        if target == 'ent_cust_cnt' :
            roleType = 1
        elif target == 'visit_cnt':
            roleType = 2
        else:
            roleType = 2
        yest_visit_cnt = myZhimindDatas.get_count_from_hour_stats_by_group(day=yesterday,roleType=roleType,max_idx=hour)
    if day == today:
        visit_cnt = get_flow_form_redis(target = target)
    else:
        visit_cnt = myZhimindDatas.get_one_target_from_rank_stats_by_group(timeType=timeType, group=group, groupType=groupType,st=day,et=day,  target=target)
    for group ,value in visit_cnt.items():
        
        if group in yest_visit_cnt.keys():
            yest_value = yest_visit_cnt[group]
        else:
            continue
        if yest_value==0:
            continue
        if value < min:continue
        if value / yest_value >=mult:
            #group_name = myRetailDatas.get_group_name(group=group)
            groupInfo = myRetailDatas.get_groups_info(groups=[group])[group]
            comp_name  = myRetailDatas.get_comp_name(shop_group=group)
            if comp_name == None:
                comp_name = ''
        
            #print 'Day(%s) GroupName(%s) GroupId(%s) City(%s) %s %s / %s >= %s'%(day,groupInfo['name'],group,groupInfo['city'],target,value,yest_value,mult)
            #logging.error('day %s group %s visit_cnt %s / %s >= 8'%(day,group,value,yest_value))
            print ','.join([day,str(group),"%s"%groupInfo['name'],"%s"%groupInfo['city'],"%s"%comp_name.encode('utf-8'),str(value),str(yest_value),str(value/yest_value)])  



if __name__ == '__main__':
    import argparse,re,datetime,time
    parser = argparse.ArgumentParser(description='args')
    parser.add_argument('--st',metavar=u"starttime",default=None)
    parser.add_argument('--et',metavar="endTime",default=None)
    parser.add_argument('--mult',metavar="",type=int,default=8)
    parser.add_argument('--target',metavar="visit_cnt",default='ent_cust_cnt')
    parser.add_argument('--min',metavar="",type=int,default=0)
    parser.add_argument('--source',metavar="",default='mysql')
    args = parser.parse_args()
    st = args.st
    et = args.et
    mult = args.mult
    target = args.target
    min = args.min
    source = args.source
    logging.basicConfig(level = logging.DEBUG)
    print ','.join(['日期','门店id','门店名','城市','所属公司','当日流量','前一天流量','环比'])
    for day in myTimeMethod.get_slist_between_st_et(st, et):
        check_flow_mutation(day=day,mult=mult,target=target,min=min,source=source)
    
